package cn.dckeji.dcssm.controller;


import cn.dckeji.dcssm.common.model.ResultModel;
import cn.dckeji.dcssm.common.utils.*;
import cn.dckeji.dcssm.entity.Park;
import cn.dckeji.dcssm.entity.Users;
import cn.dckeji.dcssm.service.ParkService;
import cn.dckeji.dcssm.service.UsersService;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Kenny
 * @since 2019-08-01
 */
@RestController
@RequestMapping("/park")
public class ParkController {

    @Autowired
    private ParkService parkService;

    @Autowired
    private UsersService usersService;
    /**
     * 分页查询管理员
     * @param pageNumber
     * @param pageSize
     * @param
     * @return
     */
    @GetMapping("/page")
    public JSONObject page(Integer pageNumber, Integer pageSize, @RequestParam(value = "parkNo",required = false) String parkNo) {
        QueryWrapper<Park> adminQueryWrapper = new QueryWrapper<>();
        adminQueryWrapper.eq("deleteFlag",0);
        adminQueryWrapper.orderByAsc("gmt_create");
        if (StringUtils.isNotBlank(parkNo)) {
            adminQueryWrapper.like("parkNo", parkNo);
        }
        IPage<Park> page = parkService.page(new Page<>(pageNumber, pageSize), adminQueryWrapper);
        List<Park> records = page.getRecords();
        List<Map> adminMapList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(records)) {
            for (Park park:records) {
                Map<String, Object> stringObjectMap = BeanUtil.beanToMap(park);
                String userId = park.getUserId();
                if(StringUtils.isNotBlank(userId)){
                    Users users = usersService.getById(userId);
                    stringObjectMap.put("userName", users.getUserName());
                    stringObjectMap.put("userPhone", users.getUserPhone());
                }else{
                    stringObjectMap.put("userName", "暂无");
                    stringObjectMap.put("userPhone", "暂无");
                }
                adminMapList.add(stringObjectMap);
            }
        }
        return ResultModel.page(page.getTotal(),  adminMapList);
    }



    /**
     * 保存管理员
     * @param
     * @return
     */
    @PostMapping("/savePark")
    public ResultModel<Object> savePark(Park park,String parkNos) {
        boolean b = parkService.savePark(park,parkNos);
        if (b) {
            return ResultModel.success();
        }else {
            return ResultModel.failure("车位号已存在,请更换重试");
        }
    }


    /**
     * 删除管理员
     * @param
     * @return
     */
    @PostMapping("/deleteById")
    public ResultModel<Object> deleteById(String parkId) {
        Park park = parkService.getById(parkId);
        JedisUtil.del(park.getParkNo().toString());
        park.setDeleteFlag(1);
        parkService.updateById(park);
        return ResultModel.success();
    }

    @ResponseBody
    @RequestMapping(value = "importData")
    public ResultModel importData(@RequestParam("file") MultipartFile[] file, HttpServletRequest request) throws IOException {
        ResultModel jsonObject = QiNiuUpLode.uploadFile(file, request,"file-excel","",false);
        List<Map> lists = (List<Map>) jsonObject.getData();
        Map map = lists.get(0);
        String string = (String) map.get("filePath");
        List<Park> studyList = ExcelUtils.readExcelToSql2(string);
        FileUtil.deleteFolder(string,true);
        if(studyList.size()<=0){
            return ResultModel.failure("不能导入空的文件");
        }
        //  EHCacheUtils cache = EHCacheUtils.getInstance();
        // cache.put("progress","progress",0);
        int count = 0;
        int size = studyList.size();
        for (int i = 0 ; i<studyList.size(); i++){
            Park study = studyList.get(i);
            Park users1 = parkService.getOne(new QueryWrapper<Park>().eq("parkNo", study.getParkNo()).eq("deleteFlag",0));
            if(null!=users1){
                 continue;
            }
            JedisUtil.set(study.getParkNo(), "", 0);
            parkService.save(study);
            //  double  my_progress = (count / (double)size)*100;
            //  if(my_progress>99){
            //       my_progress=100;
            //   }
            //  cache.put("progress","progress",  String.valueOf((new Double(my_progress)).intValue()));
            ++count;
        }
            return ResultModel.success("成功导入"+studyList.size()+"条信息");
    }


    /**
     *      导出
     * @param response
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/exportExcel3")
    public void exportExcel3(HttpServletResponse response, String parkNo2) throws Exception {
        QueryWrapper<Park> demoQueryWrapper = new QueryWrapper<>();
        demoQueryWrapper.eq("deleteFlag",0);
        demoQueryWrapper.like(StringUtils.isNotBlank(parkNo2),"parkNo",parkNo2);
        demoQueryWrapper.orderByAsc("gmt_create");
        List<Park> list = parkService.list(demoQueryWrapper);
        List< Map<String,Object>> lists = new ArrayList<>();
        for(Park park : list){
            Map<String,Object> map = new HashMap<>();
            String userId = park.getUserId();
            if(StringUtils.isNotBlank(userId)){
                Users users = usersService.getById(userId);
                map.put("userName", users.getUserName());
                map.put("userPhone", users.getUserPhone());
            }else{
                map.put("userName", "暂无");
                map.put("userPhone", "暂无");
            }
            map.put("parkNo", park.getParkNo());
            map.put("parkPrice", park.getParkPrice());
            lists.add(map);
        }
        LinkedHashMap<String, Object> titles = new LinkedHashMap<>();
        titles.put("parkNo", "车位编号");
        titles.put("parkPrice", "车位价格");
        titles.put("userName", "购买人");
        titles.put("userPhone", "购买人手机号");
        boolean excel = ExcelUtilss.toExcel(response, titles, lists, "", "车位信息导出");
    }

}

